<template>
    <div v-if="showTime" class="count-down">{{ format(showTime) }}</div>
  </template>
  <script>
  import dayjs from 'dayjs';
  
  export default {
    name: 'CountDown',
    props: {
      endTime: {
        default: '',
        type: String,
      },
      format: {
        type: Function,
        default: value => `${value}`,
      },
    },
    data() {
        return {
            showTime: '',
            timer: null
        }
    },
    mounted() {
        this.initPage()
    },
    methods: {
        initPage() {
            const endTime = this.endTime;
            const diffHours = dayjs(endTime).diff(dayjs(), 'hours');
            if (diffHours < 24 && diffHours >= 0) {
                this.showTime = this.formatTime(endTime);
                this.timer = setInterval(()=> {
                const diff = dayjs(endTime).diff(dayjs(), 'ms');
                if (diff <= 0) {
                    this.showTime = '';
                    this.$emit('finish');
                    clearInterval(this.timer);
                    return;
                }
                this.showTime = this.formatTime(endTime);
                }, 1000);
            }
  
            if (diffHours >= 24) {
                const diffDay = dayjs(endTime).diff(dayjs(), 'days');
                this.showTime = `${diffDay} 天`;
            }

        },
        formatTime(time) {
            const diffHours = dayjs(time).diff(dayjs(), 'hours');
            let showTime = '';
            if (diffHours < 24 && diffHours >= 0) {
                // 读秒 倒计时显示
                const seconds = dayjs(time).diff(dayjs(), 'seconds');
                const hour = Math.floor((seconds / (60 * 60)) % 24); //计算小时数
                const minute = Math.floor((seconds / 60) % 60); //计算分钟数
                const second = Math.floor(seconds % 60); //计算秒数
                showTime = `${hour} 时 ${minute} 分 ${second} 秒`;
            }
            return showTime;
        }
    },  
    // 组件注销
    beforeDestroy() {
        if (this.timer) {
          clearInterval(this.timer);
        }
    }

  };
  </script>
  <style lang=""></style>
  